package com.sky.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.JSON;
import com.sky.constant.MessageConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.exception.LoginFailedException;
import com.sky.mapper.UserMapper;
import com.sky.properties.WeChatProperties;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@Service
public class UserServiceImpl implements UserService {
    //创建常量
    private static final String WX_LOGIN = "https://api.weixin.qq.com/sns/jscode2session";
    //进行注入wechatProperties
    @Autowired
    private WeChatProperties weChatProperties;
    @Autowired
    private UserMapper userMapper;
    //实现微信登录
    @Override
    public User wxLogin(UserLoginDTO userLoginDTO) {
        //第一步，需要获取到微信小程序传递到服务器端的code(授权码）
        String code = userLoginDTO.getCode();
        if(code == null){
            throw new LoginFailedException(MessageConstant.LOGIN_FAILED);
        }
        //第二步，根据code和之前WechatProperties中的参数创建有效载荷(payload)
        Map<String,String> payload = new HashMap<>();
        payload.put("appid",weChatProperties.getAppid());
        payload.put("secret",weChatProperties.getSecret());
        payload.put("js_code",code);
        payload.put("grant_type", "authorization_code");
        //第三步：使用HttpClient向微信的接口发起请求，获取openid
        String json = HttpClientUtil.doGet(WX_LOGIN,payload);
        JSONObject jsonObject = JSON.parseObject(json);
        String openid = jsonObject.getString("openid");
        //第四步：根据openid查询数据库，看是否是新用户
        User user = userMapper.wxLogin(openid);
        //第五步：如果是新用户则进行注册
        if (user == null){
            user = User.builder()
                    .openid(openid)
                    .createTime(LocalDateTime.now())
                    .build();
            userMapper.insertUser(user);
        }
        return user;
    }
}
